<template>
  <a-modal title="子表单"
           v-model:visible="visible"
           :confirmLoading="confirmLoading"
           cancelText="取消"
           okText="确定"
           @ok="onFinish"
           style="min-width: 50%;"
           @cancel="()=>{visible=false}">
      <a-spin :spinning="confirmLoading">
          <a-form ref="formRef" :model="form" :labelCol="{span:6}">
              <a-row :gutter="24" v-for="(value,index) in rowList" :key="index">
                  <a-col :span="24 / value.length" v-for="(item,i) in value" :key="i">
                      <a-form-item v-if="item.e_type == 'select'" :label="item.title" :name="item.field" :rules="item">
                          <a-select v-model:value="form[item.field]" style="width: 200px" :placeholder="item.title"
                                    :options="item.data" />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'selectList'" :label="item.title" :name="item.field" :rules="item">
                          <a-select v-model:value="form[item.field]" mode="multiple" style="width: 100%" :placeholder="item.title"
                                    :options="item.data" />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'number'" :label="item.title" :name="item.field" :rules="item">
                          <a-input-number style="width:100%" v-model:value="form[item.field]" :placeholder="item.title"
                                          allow-clear />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'radio'" :label="item.title" :name="item.field" :rules="item">
                          <a-radio-group v-model:value="form[item.field]">
                              <a-radio v-for="rad in item.data" :key="rad" :value="rad.value">{{ rad.key }}</a-radio>
                          </a-radio-group>
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'textarea'" :label="item.title" :name="item.field" :rules="item">
                          <a-textarea v-model:value="form[item.field]" :placeholder="item.title" allow-clear />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'date'" :label="item.title" :name="item.field" :rules="item">
                          <a-date-picker v-model:value="form[item.field]" value-format="YYYY-MM-DD" :placeholder="item.title" />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'img'" :label="item.title" :name="item.field" :rules="item">
                          <upload-img v-model="form[item.field]" urlType="web" />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'switch'" :label="item.title" :name="item.field" :rules="item">
                          <a-switch v-model:checked="form[item.field]" :unCheckedValue="0" :checkedValue="1" />
                      </a-form-item>
                      <a-form-item v-else-if="item.e_type == 'editor'" :label="item.title" :name="item.field">
                          <Editor v-if="visible" v-model="form[item.field]" :index="index+'-'+i" />
                      </a-form-item>
                      <a-form-item v-else :label="item.title" :name="item.field" :rules="item">
                          <a-input v-model:value="form[item.field]" :placeholder="item.title" allow-clear />
                      </a-form-item>
                  </a-col>
              </a-row>
          </a-form>
          <template v-if="detail.columns && detail.columns.length > 0">
              <a-button type="primary" @click="handleAdd">
                  <template #icon>
                      <PlusOutlined />
                  </template>
                  新建
              </a-button>
              <div style="margin: 10px 0"></div>
              <a-table v-if="detail.columns && detail.columns.length > 0" :columns="detail.columns"
                       :rowKey="row => row.Id"
                       :pagination="pagination"
                       :dataSource="detailSource"
                       @change="handleTableChange"
                       :bordered="true"
                       size="small">
                  <template #bodyCell="{ column, record,index }">
                      <template v-if="column.bind && column.bind.key">
                          <a-tag :color="getColors(record,column)">{{ getColumnText(column, record) }}</a-tag>
                      </template>
                      <template v-if="column.e_type == 'img'">
                          <img v-if="record[column.key]" :src="url+record[column.key]" style="max-width: 60px;height: auto;" />
                          <a-avatar v-else :size="64">
                              <template #icon>
                                  <UserOutlined />
                              </template>
                          </a-avatar>
                      </template>
                      <template v-if="column.key == 'action'">
                          <a-button size="small" type="primary" @click="handleEdit(record.#IsKey)">编辑</a-button>
                          <a-divider type="vertical" />
                          <a-button size="small" type="primary" danger @click="handleDelete([record.#IsKey])">删除</a-button>
                      </template>
                  </template>
              </a-table>
              </template>
      </a-spin>
  </a-modal>
  <SubForm ref="subForm" :getParTable="getParTable"/>
</template>

<script setup>
import {ref, nextTick, createVNode} from "vue";
import {http} from '@/axios/'
import {message, Modal} from "ant-design-vue";
import {rowList, detail} from '../ranks'
import UploadImg from '@/components/UploadImg/index.vue'
import Editor from '@/components/Editor/index.vue'
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import SubForm from './SubForm.vue'
import {getColumnText, getColors} from '@/components/DynamicForm/index.js'

const url = import.meta.env.VITE_APP_PublishRootUrl
const visible = ref(false)
const confirmLoading = ref(false)
const form = ref({})
const formRef = ref()
const pagination = ref({
  current: 1,
  pageSize: 10,
  showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`
})
const props = defineProps({
  getDataList: {
    type: Function,
    default: () => {
    }
  }
})

async function openForm(id) {
    props.getDataList()
    try {
        init(id)
        if (id) {
            const { Success, Msg, Data } = await http.post('/%areaName%/%entityName%/GetTheData', { id })
            if (Success) {
                form.value = Data
            } else {
                message.warning(Msg)
            }
        }
    } catch (error) {
        console.log("[openForm error]:" + error.message)
    }
}

    defineExpose({ openForm })

const sonId = ref('')
function init(id) {
    visible.value = true
    if (id) {
        sonId.value = id
        if (detail.value.columns && detail.value.columns.length > 0) {
            getParTable(id);
        }
    }

    form.value = {}
    nextTick(() => {
        formRef.value.resetFields()
    })
}



async function onFinish() {
  try {
    const params = await formRef.value.validateFields()
    confirmLoading.value = true
      const { Success, Msg } = await http.post("/%areaName%/%entityName%/SaveData", form.value)
    confirmLoading.value = false
    if (Success) {
      message.success('操作成功!')
      props.getDataList();
      visible.value = false
    } else {
      message.error(Msg)
    }
  } catch (error) {
    console.log("[表单校验 error]:", error.message);
    if (error.message) {
      message.error("服务器异常!")
    }
  }
}

const detailSource = ref()

async function getParTable() {
  try {
      const { Success, Data, Total, Msg } = await http.post("/%areaName%/%SubentityName%/GetDataList", {
          PageIndex: pagination.value.current,
          PageRows: pagination.value.pageSize,
          Condition: "#SubCondition",
          Keyword: "#SubKeyword",
    })
    if (Success) {
      detailSource.value = Data
      pagination.value = {...pagination.value, total: Total}
    } else {
      message.error(Msg)
    }
  } catch (error) {
    if (error.message) {
      message.error("服务器异常!")
    }
  }
}
// 子表
function handleTableChange(page) {
    pagination.value = page
    getParTable(sonId.value)
}
const subForm = ref()


function handleEdit(id) {
    subForm.value.openForm(id, 'edit')
}
const handleAdd = () => {
    subForm.value.openForm(form.value.#IsKey, 'add')
}
function handleDelete(id) {

  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确认删除吗',
    okText: '确认删除',
    cancelText: '取消',
    onOk: async () => {
      try {
        const {
          Success,
          Msg
        } = await http.post("/%areaName%/%SubentityName%/DeleteData", id)
        if (Success) {
          message.success("操作成功")
          getParTable(sonId.value)
        } else {
          message.warning(Msg)
        }
      } catch (error) {
        message.error("服务器异常!")
      }
    }
  })
}
</script>